﻿using System;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Casamiel.Common;
using Casamiel.Common.Extensions;
using Casamiel.Domain.Response;
using MediatR;
using Microsoft.Extensions;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Casamiel.Application.Commands
{

    /// <summary>
    /// 我的会员卡信息
    /// </summary>
    public sealed class GetMemberInfoCardInfoCommandHandler : BaseCommandHandler, IRequestHandler<GetMemberInfoCardInfoCommand, BaseResult<GetMemberInfoCardInfoRsp>>
    {
        private readonly IMemberService _memberService;
        private readonly IMemberCardService _cardService;

        /// <summary>
		/// 
		/// </summary>
		/// <param name="netICService"></param>
		/// <param name="httpClientFactory"></param>
		/// <param name="optionsSnapshot"></param>
		/// <param name="memberService"></param>
		/// <param name="memberCardService"></param>
        public GetMemberInfoCardInfoCommandHandler(INetICService netICService, IHttpClientFactory httpClientFactory, IOptionsSnapshot<CasamielSettings> optionsSnapshot,
        IMemberService memberService, IMemberCardService memberCardService) : base(netICService, httpClientFactory, optionsSnapshot)
        {
            _memberService = memberService;
            _cardService = memberCardService;
        }

        /// <summary>
        /// Handle the specified request and cancellationToken.
        /// </summary>
        /// <returns>The handle.</returns>
        /// <param name="request">Request.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        public async Task<BaseResult<GetMemberInfoCardInfoRsp>> Handle(GetMemberInfoCardInfoCommand request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            if (!string.IsNullOrEmpty(request.Mobile))
            {
                var m = await _memberService.FindAsync<ICasaMielSession>(request.Mobile).ConfigureAwait(false);
                GetMemberInfoCardInfoRsp mInfo;
                if (m != null)
                {
                    mInfo = new GetMemberInfoCardInfoRsp
                    {
                        Mobile = m.Mobile,
                        Nick = m.Nick,
                        TrueName = m.TrueName,
                        Source = m.Source,
                        Birthday = m.Birthday,
                        LastLoginDate = m.LastLoginDate,
                        CreateDate = m.CreateDate,
                        CardInfoList = new System.Collections.Generic.List<CardInfoRsp>()
                    };
                    await SetCardInfo(request.Mobile, mInfo).ConfigureAwait(false);

                    return new BaseResult<GetMemberInfoCardInfoRsp>(mInfo, 0, "");
                }
            }

            if (!string.IsNullOrEmpty(request.CardNO))
            {
                GetMemberInfoCardInfoRsp mInfo;
                var cardinfo = await _cardService.FindAsync<ICasaMielSession>(request.CardNO).ConfigureAwait(false);
                if (cardinfo != null)
                {
                    var m = await _memberService.FindAsync<ICasaMielSession>(cardinfo.Mobile).ConfigureAwait(false);
                    if (m != null)
                    {
                        mInfo = new GetMemberInfoCardInfoRsp
                        {
                            Mobile = m.Mobile,
                            Nick = m.Nick,
                            TrueName = m.TrueName,
                            Source = m.Source,
                            Birthday = m.Birthday,
                            LastLoginDate = m.LastLoginDate,
                            CreateDate = m.CreateDate
                           ,
                            CardInfoList = new System.Collections.Generic.List<CardInfoRsp>()
                        };

                        await SetCardInfo(m.Mobile, mInfo,$"{request.DataSource}099".ToInt32(0)).ConfigureAwait(false);
                        return new BaseResult<GetMemberInfoCardInfoRsp>(mInfo, 0, "");
                    }

                }
                return new BaseResult<GetMemberInfoCardInfoRsp>(null, 9999, "查不到");
            }

            return new BaseResult<GetMemberInfoCardInfoRsp>(null, 9999, "查不到");
        }

        private async Task SetCardInfo(string Mobile, GetMemberInfoCardInfoRsp mInfo,int datasource=0)
        {
            var list = await _cardService.GetListAsync<ICasaMielSession>(Mobile).ConfigureAwait(false);
            var mycard = list.Where(a => a.IsBind == true).ToList();
            for (int i = 0; i < mycard.Count; i++)
            {
                var item = mycard[i];
                var zmodel = await NetICService.Iclessquery(item.CardNO, datasource).ConfigureAwait(false);
                var rnt = JsonConvert.DeserializeObject<JObject>(zmodel.content);
                if (zmodel.code == 0)
                {
                    mInfo.CardInfoList.Add(new CardInfoRsp
                    {
                        Cardno = item.CardNO,
                        Totalmoney = rnt == null ? "0" : rnt["totalmoney"].ToString(),
                        Cardtype = item.CardType,
                        Sate = $"{item.State}",
                        Source = item.Source,
                        Othermoney = rnt == null ? "0" : rnt["othermoney"].ToString(),
                        Directmoney = rnt == null ? "0" : rnt["directmoney"].ToString(),
                        BindTime = item.BindTime.Value
                    });
                }
                else if (zmodel.code == 105)
                {
                    mycard[i].IsBind = false;
                    await _cardService.UpdateAsync<ICasaMielSession>(mycard[i]).ConfigureAwait(false);
                }
            }
        }
    }
}
